package ch.zbw.pra.sysventory.domain.scanner;

import java.util.ArrayList;
import java.util.List;

import ch.zbw.pra.sysventory.domain.model.Software;
import ch.zbw.pra.sysventory.domain.model.VendorSoftware;
import ch.zbw.pra.sysventory.domain.util.MyLogger;
import ch.zbw.pra.sysventory.ui.DetailLabel;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

/**
 * Diese Classe Listet die installierten Softwarepakete unter Verwendung des
 * WMI-Interfaces auf
 * 
 * @author Silvan
 */

public class ScanSoftwares {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ScanSoftwares.class);

	// Initialise Object Data types
	private List<Software> softwares;

	// Constructor
	public ScanSoftwares() {
		// Create Listobject
		this.softwares = new ArrayList<Software>();
	}

	// Get Software
	public List<Software> getSoftware() {
		String host = "localhost";
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM win32_Product";
		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;

			while (enumVariant.hasMoreElements()) {

				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a
				// java
				// form.
				String stNameSoftware = Dispatch.call(item, "Caption").toString();
				String stVersionSoftware = Dispatch.call(item, "Version").toString();
				String stVendor = Dispatch.call(item, "Vendor").toString();
				MyLogger.logDebug(log, stNameSoftware + " " + stVersionSoftware + " " + stVendor);
				DetailLabel.setTextDetailLabel(stNameSoftware);

				VendorSoftware vendor = new VendorSoftware(stVendor);
				Software software = new Software(stNameSoftware, stVersionSoftware, vendor);
				softwares.add(software);
			}
		} catch (Exception e) {
			MyLogger.logError(log, e.toString());
		}
		return softwares;
	}
}
